<?php

namespace App\Store\Controllers\Goods;

use App\Common\Services\Store\Common as StoreCommon;
use App\Http\Controllers\Controller;
use App\Jobs\ReplenishAuditJob;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Goods\GoodsReplenish;
use App\Store\Models\Goods\GoodsReplenishInfolist;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Goods\GoodsReplenishService;
use Illuminate\Http\Request;
use App\Store\Validate\Goods\GoodsReplenish as ValidateGoodsGoodsReplenish;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use App\Common\Services\CommonExcelExport;
use App\Store\Services\Goods\Goods;

/**
 * 商品补货
 */
class GoodsReplenishController extends Controller
{
    /**
     * 商品补货单
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['store_ids', 'supply_id', 'goods_list', 'remark']);
        $Validate = new ValidateGoodsGoodsReplenish();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        if (empty($req_data['goods_list'])) {
            return response()->json(['code' => '001', 'msg' => '补货明细不能为空！']);
        }

        $store_ids = $req_data['store_ids'];
        $store_ids = is_array($store_ids) ? $store_ids : (is_array(json_decode($store_ids, true)) ? json_decode($store_ids, true) : []);

        if (count($store_ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        //处理补货商品列表
        $goods_list = $req_data['goods_list'];
        $replenish_info_data = is_array($goods_list) ? $goods_list : (is_array(json_decode($goods_list, true)) ? json_decode($goods_list, true) : []);

        DB::beginTransaction();
        try {
            foreach ($store_ids as $store_id) {
                $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $accountinfo['cp_id']])->first();
                if (!$storeinfo) {
                    return response()->json(['code' => '001', 'msg' => '无效门店参数']);
                }

                $goods_count = 0;
                foreach ($replenish_info_data as $v) {
                    $goods_count += $v['count_new'];
                }

                //补货单
                $replenish_data = [
                    'cp_id' => $cp_id,
                    'store_id' => $store_id,
                    'order_sncode' => StoreCommon::createOrderSn(),
                    'goods_count' => $goods_count,
                    'supply_id' => $req_data['supply_id'] ?? 0,
                    'remark' => $req_data['remark'],
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                ];
                $replenish_id = GoodsReplenish::create($replenish_data)->id;

                //补货明细
                $replenishArr = [];
                if ($replenish_info_data) {
                    foreach ($replenish_info_data as $k => $v) {
                        if ($v['count_new'] <= 0) {
                            return response()->json(['code' => '001', 'msg' => '商品补货不能为负！']);
                        }

                        $total_piece_weight_new = 0;
                        $is_code_more = $v['is_code_more'] ?? 1;
                        $v['repllennish_costglod_price'] = ($v['repllennish_costglod_price'] ?? 0) * 100;
                        $v['costglod_price'] = $v['costglod_price'] ?? 0;
                        $is_gram = $v['goods_category']['is_gram'] ?? 0;
                        if ($is_code_more == 2) {
                            $total_netglod_weight_new = $v['total_netglod_weight'] ?? 0;
                        } else {
                            $total_netglod_weight_new = $v['netglod_weight'] * $v['count_new'];
                            $total_piece_weight_new = $v['piece_weight'] * $v['count_new'];
                        }
                        // 追加
                        $v['cp_id'] = $cp_id;
                        $v['order_sncode'] = $replenish_data['order_sncode'];
                        $v['store_id'] = $store_id;
                        $v['p_id'] = $replenish_id;
                        $v['total_piece_weight_new'] = $total_piece_weight_new;
                        $v['total_netglod_weight_new'] = $total_netglod_weight_new;
                        $v['total_piece_weight'] = $total_piece_weight_new;
                        $v['total_netglod_weight'] = $total_netglod_weight_new;
                        $v['create_account_id'] = $accountinfo['id'];
                        $v['create_account_real_name'] = $accountinfo['real_name'];
                        $v['create_at'] = time();
                        $v['count'] = $v['count_new'] ?? 0;
                        unset($v['id'], $v['allot_count'], $v['goods_brand'], $v['goods_category'], $v['goods_craft'],
                            $v['goods_pricetype'], $v['goods_stone'], $v['goods_style'], $v['odds'], $v['paytype_info'],
                            $v['pricetype'], $v['sales_count'], $v['start_stockin_store_id'], $v['startstoreinfo'], $v['storeinfo'],
                            $v['supply'], $v['goods_content'], $v['goods_content_id'], $v['electronic_scale'], $v['total_netglod_weight1']
                        );

                        if ((int)$v['repllennish_costglod_price'] == 0) {
                            // 采用原始的公式计算
                            $total_cost_fee = (new Goods())->computeOriginalTotalCost($v, $is_gram);
                            $v['total_cost_fee'] = $total_cost_fee;
                        } else {
                            // 采用补货的公式计算
                            list($piececost_fee, $total_cost_fee) = (new GoodsReplenishService())->replenishTotalCost($v, $is_gram);
                            $v['piececost_fee'] = $piececost_fee;
                            $v['total_cost_fee'] = $total_cost_fee;
                        }

                        $replenishArr[] = $v;
                    }
                }

                GoodsReplenishInfolist::query()->insert($replenishArr);
            }


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            info('商品补货失败' . $e->getFile() . $e->getLine() . $e->getMessage());
            return response()->json(['code' => '001', 'msg' => '添加失败']);
        }
        return response()->json(['code' => '000', 'msg' => '商品补货成功']);
    }


    /**
     *  编辑
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function dopostedit(Request $request)
    {
        $params = $request->only(['id', 'supply_id']);
        $info = GoodsReplenish::query()->where(['id'=>$params['id'],'is_del'=>1])->first();

        if(empty($info)){
            return response()->json(['code' => '001', 'msg' => '补货订单信息不存在']);
        }

        GoodsReplenish::query()->where(['id'=>$params['id'],'is_del'=>1])->update(['supply_id'=>$params['supply_id']]);
        GoodsReplenishInfolist::query()->where(['p_id'=>$params['id'],'is_del'=>1])->update(['supply_id'=>$params['supply_id']]);

        return response()->json(['code' => '000', 'msg' => '修改成功']);
    }

    /**
     * 商品补货单
     */
    public function dopostaddnegative(Request $request)
    {
        $req_data = $request->only(['store_ids', 'supply_id', 'goods_list', 'remark']);
        $Validate = new ValidateGoodsGoodsReplenish();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        if (empty($req_data['goods_list'])) {
            return response()->json(['code' => '001', 'msg' => '补货明细不能为空！']);
        }

        $store_ids = $req_data['store_ids'];
        $store_ids = is_array($store_ids) ? $store_ids : (is_array(json_decode($store_ids, true)) ? json_decode($store_ids, true) : []);

        if (count($store_ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        //处理补货商品列表
        $goods_list = $req_data['goods_list'];
        $replenish_info_data = is_array($goods_list) ? $goods_list : (is_array(json_decode($goods_list, true)) ? json_decode($goods_list, true) : []);

        DB::beginTransaction();
        try {
            foreach ($store_ids as $store_id) {
                $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $accountinfo['cp_id']])->first();
                if (!$storeinfo) {
                    return response()->json(['code' => '001', 'msg' => '无效门店参数']);
                }

                $goods_count = 0;
                foreach ($replenish_info_data as $v) {
                    $goods_count += $v['count_new'];
                }

                //补货单
                $replenish_data = [
                    'cp_id' => $cp_id,
                    'store_id' => $store_id,
                    'order_sncode' => StoreCommon::createOrderSn(),
                    'goods_count' => $goods_count,
                    'supply_id' => $req_data['supply_id'] ?? 0,
                    'remark' => $req_data['remark'],
                    'audit_status' => 3,
                    'audit_success_count' => abs($goods_count),
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                ];
                $replenish_id = GoodsReplenish::create($replenish_data)->id;

                $replenishArr = [];
                if ($replenish_info_data) {
                    foreach ($replenish_info_data as $k => $v) {
                        if ($v['count_new'] >= 0) {
                            return response()->json(['code' => '001', 'msg' => '商品补货不能为正！']);
                        }

                        $is_code_more = $v['is_code_more'] ?? 1;
                        $v['repllennish_costglod_price'] = $v['repllennish_costglod_price'] ?? 0;
                        $v['costglod_price'] = $v['costglod_price'] ?? 0;
                        $avg_costglod_price = $v['repllennish_costglod_price'] > 0 ? (bcdiv(bcadd($v['costglod_price'], $v['repllennish_costglod_price']), 2)) : $v['costglod_price'];
                        $total_piece_weight_new = 0;
                        if ($is_code_more == 2) {
                            $total_netglod_weight_new = $v['total_netglod_weight'] ?? 0;
                            $v['total_cost_fee'] = bcmul($avg_costglod_price, $total_netglod_weight_new);
                        } else {
                            $total_netglod_weight_new = $v['netglod_weight'] * abs($v['count_new']);
                            $total_piece_weight_new = $v['piece_weight'] * abs($v['count_new']);
                            $is_gram = $v['goods_category']['is_gram'] ?? 0;
                            if ($is_gram == 1) {
                                $v['total_cost_fee'] = bcmul((string)(($v['costgram_fee'] ?? 0) + $avg_costglod_price), $v['total_netglod_weight'], 0) + ($v['costpiece_fee'] ?? 0) * abs($v['count_new']);
                            } else {
                                $v['total_cost_fee'] = ($v['piececost_fee'] ?? 0) * abs($v['count_new']);
                            }
                        }

                        // 追加
                        $v['cp_id'] = $cp_id;
                        $v['store_id'] = $store_id;
                        $v['p_id'] = $replenish_id;
                        $v['total_piece_weight_new'] = $total_piece_weight_new;
                        $v['total_netglod_weight_new'] = $total_netglod_weight_new;
                        $v['audit_status'] = 2;
                        $v['audit_success_count'] = abs($v['count_new']);
                        $v['create_account_id'] = $accountinfo['id'];
                        $v['create_account_real_name'] = $accountinfo['real_name'];
                        $v['create_at'] = time();
                        unset($v['id'], $v['allot_count'], $v['goods_brand'], $v['goods_category'], $v['goods_craft'], $v['goods_pricetype'], $v['goods_stone'], $v['goods_style'], $v['odds'], $v['paytype_info'], $v['pricetype'], $v['sales_count'], $v['start_stockin_store_id'], $v['startstoreinfo'], $v['storeinfo'], $v['supply'], $v['goods_content'], $v['goods_content_id'], $v['electronic_scale']);

                        $stock = GoodsStockList::query()
                            ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'is_del' => 1, 'goods_sn_code' => $v['goods_sn_code']])
                            ->first();

                        $stock = empty($stock) ? [] : $stock->toArray();
                        if (empty($stock)) {
                            return response()->json(['code' => '001', 'msg' => '商品不存在']);
                        }

                        $replenishArr[] = $v;

                        $update = [];
                        $update['count'] = $stock['count'] - abs($v['count_new']);
                        $update['total_piece_weight'] = $stock['total_piece_weight'] > 0 ? ($stock['total_piece_weight'] - abs($total_piece_weight_new)) : 0;
                        $update['total_netglod_weight'] = $stock['total_netglod_weight'] > 0 ? $stock['total_netglod_weight'] - abs($total_netglod_weight_new) : 0;

                        if ($update['count'] < 0) {
                            return response()->json(['code' => '001', 'msg' => '商品补货后，库存不能小于0']);
                        }

                        $update['total_cost_fee'] = (new Goods())->computeTotalCost($stock, $update['total_netglod_weight'], $update['count']);

                        // 库存添加数量、总金重、总件重
                        GoodsStockList::query()->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'goods_sn_code' => $v['goods_sn_code']])->update($update);

                        Goods::goodsLog($request, 0, $v['store_id'], $v, $v['count_new'], 3, $replenish_data['order_sncode']);
                    }
                }

                GoodsReplenishInfolist::query()->insert($replenishArr);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '商品补货成功']);
    }

    /**
     * 导入
     * 只导入一个单子
     */
    public function doimport(Request $request)
    {
        $req_data = $request->only(['store_id', 'supply_id']);
        $Validate = new ValidateGoodsGoodsReplenish('import');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0];
            if (count($data) <= 1) {
                return response()->json(['code' => '001', 'msg' => '导入失败，数据为空']);
            }
            $return_msg = '';

            if (count($data) > 1001) {
                return response()->json(['code' => '001', 'msg' => '超过导入数据上限，最多导入1000条']);
            }

            try {
                $store_id = $req_data['store_id'];
                $accountinfo = StoreCommon::getCurrentAccountinfo($request);
                $cp_id = $accountinfo['cp_id'];

                $order_sncode = StoreCommon::createOrderSn();
                $replenish_id_data = [
                    'cp_id' => $cp_id,
                    'store_id' => $store_id,
                    'order_sncode' => $order_sncode,
                    'supply_id' => $req_data['supply_id'] ?? 0,
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                ];

                //返厂单
                $replenish_id = GoodsReplenish::query()->create($replenish_id_data)->id;
                $replenish = [];
                $sum = 0;
                foreach ($data as $key => $val) {
                    //表头跳过
                    if ($key == 0) {
                        continue;
                    }

                    if (empty($val)) {
                        $return_msg .= '导入失败，第【' . $key . '】行条码为空;';
                        continue;
                    }

                    //库存查看商品信息
                    $goods = GoodsStockList::query()
                        ->where('cp_id', $cp_id)
                        ->where('goods_sn_code', trim($val[0]))
                        ->where('is_del', 1)
                        ->first();
                    if (!empty($goods)) {


                        $goods = $goods->toArray();
                        if (trim($val[1]) == '否') {
                            $is_code_more = 1;
                            $total_piece_weight = (int)trim($val[2]) * (float)$goods['piece_weight'];
                            $total_netglod_weight = (int)trim($val[2]) * (float)$goods['netglod_weight'];

                        } else {
                            $is_code_more = 2;
                            //一码多货
                            $total_piece_weight = 0;
                            $total_netglod_weight = $val[3] ?? 0;
                        }

                        $count_new = trim($val[2]);
                        if ($count_new < 0) {
                            $return_msg .= '导入失败，条码【' . $val[0] . '】，补货不能导入负数;';
                            continue;
                        }

                        if ($goods['is_code_more'] != $is_code_more) {
                            $return_msg .= '导入失败，条码【' . $val[0] . '】，一码多货状态和库存不一致;';
                            continue;
                        }

                        if (preg_match('/^-?(?:\d+\.\d+|\.\d+|\d+)$/', $total_piece_weight) == false) {
                            $return_msg .= '导入失败，条码【' . $val[0] . '】，总件重填写的有问题，存在=、+号;';
                            continue;
                        }

                        if (preg_match('/^-?(?:\d+\.\d+|\.\d+|\d+)$/', $total_netglod_weight) == false) {
                            $return_msg .= '导入失败，条码【' . $val[0] . '】，总金重填写的有问题，存在=、+号;';
                            continue;
                        }


                        $goods['total_netglod_weight'] = $total_netglod_weight;
                        // 补货金价
                        $goods['repllennish_costglod_price'] = ($val[4] ?? 0) * 100;

                        $category = GoodsCategory::query()
                            ->where(['cp_id' => $cp_id, 'is_del' => 1, 'id' => $goods['goods_category_id']])
                            ->first();

                        if (empty($category)) {
                            return response()->json(['code' => '001', 'msg' => '类别不存在不能审核']);
                        }
                        $category = $category->toArray();
                        $goods['total_piece_weight'] = $total_piece_weight;
                        $goods['total_netglod_weight'] = $total_netglod_weight;
                        $goods['count'] = $count_new;
                        $goods['order_sncode'] = $order_sncode;
                        $goods['cp_id'] = $cp_id;
                        $goods['store_id'] = $store_id;
                        $goods['p_id'] = $replenish_id;
                        $goods['count_new'] = $count_new;
                        $goods['create_account_id'] = $accountinfo['id'];
                        $goods['create_account_real_name'] = $accountinfo['real_name'];
                        $goods['create_at'] = time();
                        $goods['total_piece_weight'] = $total_piece_weight;
                        $goods['total_netglod_weight'] = $total_netglod_weight;
                        // 最新的总金重，重件重
                        $goods['total_piece_weight_new'] = $goods['total_piece_weight'];
                        $goods['total_netglod_weight_new'] = $goods['total_netglod_weight'];
                        if ($count_new < 0) {
                            $piececost_fee = $goods['piececost_fee'] ?? 0;
                            $total_cost_fee = (new Goods())->computeOriginalTotalCost($goods, $category['is_gram']);
                        } else {
                            if ((int)$goods['repllennish_costglod_price'] == 0) {
                                // 采用原始的公式计算
                                $piececost_fee = $goods['piececost_fee'] ?? 0;
                                $total_cost_fee = (new Goods())->computeOriginalTotalCost($goods, $category['is_gram']);
                            } else {
                                // 采用补货的公式计算
                                list($piececost_fee, $total_cost_fee) = (new GoodsReplenishService())->replenishTotalCost($goods, $category['is_gram']);
                            }
                        }
                        // 追加
                        $goods['total_cost_fee'] = $total_cost_fee;
                        $goods['piececost_fee'] = $piececost_fee;

                        // 删除不需要的参数
                        unset($goods['id'], $goods['allot_count'], $goods['sales_count'], $goods['start_stockin_store_id'], $goods['create_at'], $goods['del_at'], $goods['pricetype'], $goods['odds'], $goods['goods_content_id'], $goods['electronic_scale']);
                        $replenish[] = $goods;

                        $sum += abs($count_new);
                    } else {
                        $return_msg .= '导入失败，条码【' . $key . '】，商品不存在。';
                    }
                }

                if (!empty($return_msg)) {
                    return response()->json(['code' => '001', 'msg' => '添加失败' . $return_msg]);
                }

                DB::beginTransaction();

                GoodsReplenish::where(['id' => $replenish_id])->update(['goods_count' => $sum]);

                if (!empty($replenish)) {
                    GoodsReplenishInfolist::query()->insert($replenish);
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getMessage()]);
            }
        }
        return response()->json(['code' => '000', 'msg' => '商品补货导入成功']);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $id = $request['id'];
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $type = $request->type ?? 3;
        $ids = $request['ids'];
        $id = $request['id'];

        $where = [];
        $store_id = $request['store_id'] ?? 0;

        if ($store_id > 0) {
            $where[] = ['store_id', $store_id];
        }
        $order_sncode = $request->order_sncode;
        if ($order_sncode != '') {
            $where[] = ['order_sncode', 'like', '%' . $order_sncode . '%'];
        }

        $goods_style_id = (int)$request->goods_style_id;
        if ($goods_style_id > 0) {
            $where[] = ['goods_style_id', $goods_style_id];
        }

        $goods_category_id = (int)$request->goods_category_id;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $audit_status = (int)$request->audit_status;
        if ($audit_status > 0) {
            $where[] = ['audit_status', $audit_status];
        }

        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        if ($type == 1) {
            $query = GoodsReplenishInfolist::with(['goods_category'])
                ->where(['p_id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])
                ->where($where);

            if (count($ids) > 0) {
                $query->whereIn('goods_category_id', $ids);
            }

            $list = $query->groupBy('goods_category_id')
                ->select('goods_category_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count_new) as label_price,sum(label_price_new*count_new) as label_price_new,sum(netglod_weight*count_new) as netglod_weight,sum(netglod_weight_new*count_new) as netglod_weight_new,sum(piece_weight*count_new) as piece_weight,sum(piece_weight_new*count_new) as piece_weight_new'))
                ->get()->toArray();

            $row = [
                ['table_header' => '商品补货信息-补货汇总'],
                [
                    'audit_status' => '状态',
                    'category_name' => '入库类别',
                    'category_name1' => '商品类别',
                    'goods_style' => '款式',
                    'count' => '数量',
                    'allotcount' => '调拨数量',
                    'audit_count' => '已审数量',
                    'not_audit_count' => '未审数量',
                    'audit_failed_count' => '驳回数量',
                    'label_price' => '入库标签价',
                    'label_price_new' => '标签价',
                    'total_netglod_weight' => '入库总金重',
                    'total_netglod_weight_new' => '总金重',
                    'total_piece_weight' => '入库总件重',
                    'total_piece_weight_new' => '总件重',
                ]];

            $exceldata = [];
            foreach ($list as $val) {
                $exceldata[] = [
                    'audit_status' => $val['audit_success_count'] == 0 && $val['audit_failed_count'] == 0 ? '待审核' : (($val['audit_success_count'] + $val['audit_failed_count']) == abs($val['count_new']) ? '审核' : '审核中'),
                    'category_name' => $val['goods_category']['category_name'],
                    'category_name1' => $val['goods_category']['category_name'],
                    'goods_style' => '--',
                    'count' => $val['count_new'],
                    'allotcount' => '--',
                    'audit_count' => ($val['audit_success_count'] + $val['audit_failed_count']),
                    'not_audit_count' => $val['count_new'] - ($val['audit_success_count'] + $val['audit_failed_count']),
                    'audit_failed_count' => $val['audit_failed_count'],
                    'label_price' => $val['label_price'] / 100,
                    'label_price_new' => $val['label_price_new'] / 100,
                    'total_netglod_weight' => $val['netglod_weight'] / 100,
                    'total_netglod_weight_new' => $val['netglod_weight_new'] / 100,
                    'total_piece_weight' => $val['piece_weight'] / 100,
                    'total_piece_weight_new' => $val['piece_weight_new'] / 100,
                ];
            }
        } else if ($type == 2) {
            $query = GoodsReplenishInfolist::with(['goods_style'])
                ->where(['p_id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])
                ->where($where);

            if (count($ids) > 0) {
                $query->whereIn('goods_style_id', $ids);
            }

            $list = $query->groupBy('goods_style_id')
                ->select('goods_style_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count) as label_price,sum(label_price_new*count_new) as label_price_new,sum(netglod_weight*count_new) as netglod_weight,sum(netglod_weight_new*count_new) as netglod_weight_new,sum(piece_weight*count_new) as piece_weight,sum(piece_weight_new*count_new) as piece_weight_new'))
                ->get()->toArray();

            $row = [
                ['start_store' => '商品补货信息-按款式汇总'],
                [
                    'audit_status' => '状态',
                    'goods_style' => '款式',
                    'category_name' => '入库类别',
                    'category_name1' => '商品类别',
                    'count' => '数量',
                    'allotcount' => '调拨数量',
                    'audit_count' => '已审数量',
                    'not_audit_count' => '未审数量',
                    'audit_failed_count' => '驳回数量',
                    'label_price' => '入库标签价',
                    'label_price_new' => '标签价',
                    'total_netglod_weight' => '入库总金重',
                    'total_netglod_weight_new' => '总金重',
                    'total_piece_weight' => '入库总件重',
                    'total_piece_weight_new' => '总件重',
                ]];

            $exceldata = [];
            foreach ($list as $val) {
                $exceldata[] = [
                    'audit_status' => $val['audit_success_count'] == 0 && $val['audit_failed_count'] == 0 ? '待审核' : (($val['audit_success_count'] + $val['audit_failed_count']) == abs($val['count_new']) ? '审核' : '审核中'),
                    'goods_style' => $val['goods_style'] ? $val['goods_style']['style_name'] : '--',
                    'category_name' => '--',
                    'category_name1' => '--',
                    'count' => $val['count_new'],
                    'allotcount' => '--',
                    'audit_count' => ($val['audit_success_count'] + $val['audit_failed_count']),
                    'not_audit_count' => $val['count_new'] - ($val['audit_success_count'] + $val['audit_failed_count']),
                    'audit_failed_count' => $val['audit_failed_count'],
                    'label_price' => $val['label_price'] / 100,
                    'label_price_new' => $val['label_price_new'] / 100,
                    'total_netglod_weight' => $val['netglod_weight'] / 100,
                    'total_netglod_weight_new' => $val['netglod_weight_new'] / 100,
                    'total_piece_weight' => $val['piece_weight'] / 100,
                    'total_piece_weight_new' => $val['piece_weight_new'] / 100,
                ];
            }
        } else {
            // 传入ids，数组
            $request['cp_id'] = $cp_id;
            $request['store_id'] = $request['store_id'] ?? 0;
            $list = GoodsReplenishInfolist::getExportList($request)['list'];
            $row = [
                ['start_store' => '商品补货信息明细'],
                [
                    'store' => '所属门店',
                    'category_name' => '入库类别',
                    'category_name_2' => '商品类别',
                    'goods_url' => '商品图片',
                    'goods_sn_code' => '条码',
                    'goods_name' => '品名',
                    'style_name' => '款式',
                    'label_price' => '入库标签价',
                    'label_price_new' => '标签售价',
                    'piece_weight' => '入库重量',
                    'piece_weight_new' => '重量',
                    'netglod_weight' => '入库金重',
                    'netglod_weight_new' => '金重',
                    'total_piece_weight' => '入库总重量', //piece_weight*count
                    'total_piece_weight_new' => '总重量', //piece_weight_new*count
                    'gramprice_fee' => '克销工费',
                    'pieceprice_fee' => '件销工费',
                    'costglod_price' => '金价',
                    'repllennish_costglod_price' => '补货金价',
                    'costpiece_fee' => '件成本工费',
                    'costgram_fee' => '克成本工费',
                    'total_cost_fee' => '总成本',
                    'content' => '含量',
                    'count' => '库存数量',
                    'count_new' => '补货数量',
                    'allot_count' => '调拨数量',
                    'cf_no' => '证书号',
                    'cf_no_gia' => 'GIA证书号',
                    'main_stone_weigth' => '主石重',
                    'main_stone_count' => '主石数',
                    'main_stone_val' => '主石值',
                    'other_stone_weigth' => '副石重',
                    'other_stone_count' => '副石数',
                    'other_stone_val' => '副石值',
                    'color' => '颜色',
                    'clarity' => '净度',
                    'cut' => '切工',
                ]];

            $is_store_account = StoreCommon::getIsStoreAccount($request);
            if (!$is_store_account) {
                unset($row[1]['supply_name']);
                unset($row[1]['paymoney']);
                unset($row[1]['costpiece_fee']);
                unset($row[1]['costgram_fee']);
                unset($row[1]['total_cost_fee']);
                unset($row[1]['repllennish_costglod_price']);
            }

            $exceldata = [];
            foreach ($list as $val) {
                $exceldata[] = [
                    'store' => $val['storeinfo']['store_name'] ?? '',
                    'category_name' => $val['goods_category']['category_name'] ?? '',
                    'category_name_2' => $val['goods_category']['category_name'] ?? '',
                    'goods_img' => $val['goods_img'],
                    'goods_sn_code' => $val['goods_sn_code'],
                    'goods_name' => $val['goods_name'],
                    'style_name' => $val['goods_style']['style_name'] ?? '',
                    'label_price' => $val['label_price'] / 100,
                    'label_price_new' => $val['label_price_new'] / 100,
                    'piece_weight' => $val['piece_weight'],
                    'piece_weight_new' => $val['piece_weight_new'],
                    'netglod_weight' => $val['netglod_weight'],
                    'netglod_weight_new' => $val['netglod_weight_new'],
                    'total_piece_weight' => (int)$val['goods_category']['is_gram']==1?($val['total_netglod_weight'] ?? 0): ($val['total_piece_weight'] ?? 0), //piece_weight*count
                    'total_piece_weight_new' => (int)$val['goods_category']['is_gram']==1?($val['total_netglod_weight_new'] ?? 0): ($val['total_piece_weight_new'] ?? 0), //piece_weight*count
                    'gramprice_fee' => $val['gramprice_fee'] / 100,
                    'pieceprice_fee' => $val['pieceprice_fee'] / 100,
                    'costglod_price' => $val['costglod_price'] / 100,
                    'repllennish_costglod_price' => $val['repllennish_costglod_price'] / 100,
                    'costpiece_fee' => $val['costpiece_fee'] / 100,
                    'costgram_fee' => $val['costgram_fee'] / 100,
                    'total_cost_fee' => $val['total_cost_fee']>0? ($val['total_cost_fee'] / 100): '',
                    'content' => $val['content'],
                    'count' => $val['count'],
                    'count_new' => $val['count_new'],
                    'allot_count' => $val['allot_count'],
                    'cf_no' => $val['cf_no'],
                    'cf_no_gia' => $val['cf_no_gia'],
                    'main_stone_weigth' => $val['main_stone_weigth'],
                    'main_stone_count' => $val['main_stone_count'],
                    'main_stone_val' => $val['main_stone_val'],
                    'other_stone_weigth' => $val['other_stone_weigth'],
                    'other_stone_count' => $val['other_stone_count'],
                    'other_stone_val' => $val['other_stone_val'],
                    'color' => $val['color'],
                    'clarity' => $val['clarity'],
                    'cut' => $val['cut'],
                ];
            }
        }

        $filename = '商品补货信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 模板下载
     */
    public function dotemplate()
    {
        $row = [[
            'store_name' => '条码',
            'is_code_more' => '是否一码多货',
            'real_name' => '补货数',
            'total_netglod_weight' => '总金重',
            'repllennish_costglod_price' => '补货金价',
        ]];

        $options = [
            'B' => ['否', '是']
        ];

        $datawith = [
            'A' => '25', 'B' => '25', 'C' => '25', 'D' => '25', 'E' => '25',
        ];

        $filename = '商品补货导入模板_' . time() . '.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $list = GoodsReplenish::getList($request);

        //统计明细中商品数、审核数、驳回数、应付账款
        if ($list) {
            foreach ($list['list'] as &$val) {
                //商品数
                $val['goods_count'] = GoodsReplenishInfolist::where(['p_id' => $val['id']])->sum('count_new');
                //审核成功
                $val['review_num'] = GoodsReplenishInfolist::where(['p_id' => $val['id'], 'audit_status' => 2])->sum('count_new');
                //审核取消
                $val['reject_num'] = GoodsReplenishInfolist::where(['p_id' => $val['id'], 'audit_status' => 3])->sum('count_new');
                //应付账款
                $val['total_paymoney'] = GoodsReplenishInfolist::where(['p_id' => $val['id']])->sum('paymoney');
            }
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 查看明细
     */
    public function getinfolist(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = GoodsReplenish::with(['storeinfo'])->where(['id' => $id, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $where = [];
        $goods_sn_code = $request->order_sncode ?? '';
        if ($goods_sn_code != '') {
            $where[] = ['goods_sn_code', 'like', '%' . $goods_sn_code . '%'];
        }

        $goods_style_id = $request->goods_style_id ?? 0;
        if ($goods_style_id > 0) {
            $where[] = ['goods_style_id', $goods_style_id];
        }

        $goods_category_id = $request->goods_category_id ?? 0;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $audit_status = $request->audit_status ?? 0;

        //按照类别汇总
        $list1_new = $list2_new = [];
        $list1 = GoodsReplenishInfolist::with(['goods_category'])->where(['p_id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->where($where)
            ->groupBy('goods_category_id')
            ->select('goods_category_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count_new) as label_price,sum(label_price_new*count_new) as label_price_new,sum(total_netglod_weight) as netglod_weight,sum(total_netglod_weight_new) as netglod_weight_new,sum(total_piece_weight) as piece_weight,sum(total_piece_weight_new) as piece_weight_new,sum(allot_count) as allot_count,sum(total_cost_fee) as total_cost_fee'))
            ->get()->toArray();
        if ($list1) {
            foreach ($list1 as $k => $v) {
                if ($v['audit_failed_count'] + $v['audit_success_count'] == abs($v['count_new'])) {
                    $status = 3;
                } elseif ($v['audit_failed_count'] + $v['audit_success_count'] < abs($v['count_new'])) {
                    if ($v['audit_failed_count'] == 0 && $v['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list1[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        unset($list1[$k]);
                    }
                }
            }
            $list1_new = array_values($list1);
        }

        //按照款式汇总
        $list2 = GoodsReplenishInfolist::with(['goods_style'])->where(['p_id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->where($where)
            ->groupBy('goods_style_id')
            ->select('goods_style_id', DB::raw('sum(count_new) as count_new,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(label_price*count_new) as label_price,sum(label_price_new*count_new) as label_price_new,sum(total_netglod_weight) as netglod_weight,sum(total_netglod_weight_new) as netglod_weight_new,sum(total_piece_weight) as piece_weight,sum(total_piece_weight_new) as piece_weight_new,sum(allot_count) as allot_count,sum(total_cost_fee) as total_cost_fee'))
            ->get()->toArray();
        if ($list2) {
            foreach ($list2 as $k => $v) {
                if ($v['audit_failed_count'] + $v['audit_success_count'] == abs($v['count_new'])) {
                    $status = 3;
                } elseif ($v['audit_failed_count'] + $v['audit_success_count'] < abs($v['count_new'])) {
                    if ($v['audit_failed_count'] == 0 && $v['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list2[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        unset($list2[$k]);
                    }
                }
            }
            $list2_new = array_values($list2);
        }

        //查询子订单详情
        $list3_query = GoodsReplenishInfolist::with(['goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'brand'])->where(['p_id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->where($where);
        if ($audit_status > 0) {
            $list3_query->where('audit_status', $audit_status);
        }
        $list3 = $list3_query->get()->toArray();

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info, 'list1' => $list1_new, 'list2' => $list2_new, 'list3' => $list3]]);
    }

    /**
     * 审核成功
     */
    public function doauditsuccess(Request $request)
    {
        $p_id = $request->p_id;
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);

        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id = (int)$accountinfo['store_ids'];

        // 待操作的明细
        if (count($goods_category_ids) > 0) {
            $infolist = GoodsReplenishInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();

        } else {
            if (count($goods_style_ids) > 0) {
                $infolist = GoodsReplenishInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = GoodsReplenishInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();
            }
        }

        if (empty($infolist)) {
            return response()->json(['code' => '001', 'msg' => '请选择正确的数据']);
        }


        dispatch(new ReplenishAuditJob($infolist, $accountinfo))->onConnection('redis')->onQueue(ReplenishAuditJob::QUEUE_JOB);

        return response()->json(['code' => '000', 'msg' => '补货单审核成功']);
    }

    /**
     * 审核成功
     */
    public function doauditsuccessmore(Request $request)
    {
        $p_ids = $request->p_ids;
        $p_ids = is_array($p_ids) ? $p_ids : (is_array(json_decode($p_ids, true)) ? json_decode($p_ids, true) : []);

        if (count($p_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        // 待操作的明细
        $infolist = GoodsReplenishInfolist::where(['cp_id' => $cp_id, 'audit_status' => 1])
            ->whereIn('p_id', $p_ids)
            ->get()
            ->toArray();
        if (empty($infolist)) {
            return response()->json(['code' => '001', 'msg' => '已审核的数据不能再次审核']);
        }

        dispatch(new ReplenishAuditJob($infolist, $accountinfo))->onConnection('redis')->onQueue(ReplenishAuditJob::QUEUE_JOB);

        return response()->json(['code' => '000', 'msg' => '补货单审核成功']);
    }

    /**
     * 取消
     */
    public function doauditcancel(Request $request)
    {

        $p_id = $request->p_id;
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);

        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id = (int)$accountinfo['store_ids'];

        if (count($goods_category_ids) > 0) {
            $infolist = GoodsReplenishInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();
        } else {
            if (count($goods_style_ids) > 0) {
                $infolist = GoodsReplenishInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = GoodsReplenishInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();
            }
        }

        DB::beginTransaction();
        try {
            $count = 0;
            $upsertData=[];
            foreach ($infolist as $info) {
                $count += $info['count_new'] ?? 0;

                $upsert=[
                    'id' => $info['id'],
                    'cp_id' => $cp_id,
                    'store_id' => $store_id,
                    'audit_status'=>3,
                    'audit_failed_count'=> abs($info['count_new']),
                    'audit_at' => time()
                ];

//                GoodsReplenishInfolist::query()
//                    ->where(['id' => $info['id'], 'cp_id' => $cp_id, 'store_id' => $store_id])
//                    ->update([
//                        'audit_status' => 3,
//                        'audit_failed_count' => abs($info['count_new']),
//                        'audit_at' => time()
//                    ]);

                   $upsertData[]=$upsert;
            }

            if(!empty($upsertData)){
                GoodsReplenishInfolist::query()->upsert($upsertData,['id'],['audit_status','audit_failed_count','audit_at']);

                $audit_status_count = GoodsReplenishInfolist::query()
                    ->where(['p_id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id, 'audit_status' => 1])
                    ->count();
                if ($audit_status_count > 0) {
                    $audit_status = 2;
                } else {
                    $audit_status = 3;
                }

                // 审核取消数
                GoodsReplenish::query()
                    ->where(['id' => $p_id, 'cp_id' => $cp_id, 'store_id' => $store_id])
                    ->increment('audit_failed_count', $count, ['audit_status' => $audit_status]);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '补货单审核取消成功']);
    }

    /**
     * 删除明细
     */
    public function dopostdelinfolist(Request $request)
    {
        $id = $request->id ?? 0;
        DB::beginTransaction();
        try {
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);

            $info = GoodsReplenish::query()->where('cp_id', $accountinfo['cp_id'])->where('id', $id)->first();
            if (empty($info)) {
                return response()->json(['code' => '001', 'msg' => '补货数据不存在无法删除']);
            }

            $del = [
                'is_del' => 2,
                'update_account_id' => $accountinfo['id'],
                'update_account_real_name' => $accountinfo['real_name'],
                'del_at' => time(),
            ];

            GoodsReplenish::query()
                ->where('id', $id)
                ->where('cp_id', $accountinfo['cp_id'])
                ->update($del);

            // 删除明细
            GoodsReplenishInfolist::query()
                ->where('cp_id', $accountinfo['cp_id'])
                ->where('p_id', $id)
                ->update($del);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '删除失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }
}
